<template>
  <div>
    <van-nav-bar left-arrow @click="$router.push('/article')"/>
    <h3>短信登录</h3>
    <van-form @submit="onSubmit">
        <van-field v-model="mobile" type="tel" placeholder="请输入手机号" name="mobile" :rules="[{ pattern: /^(?:(?:\+|00)86)?1\d{10}$/, message: '请填写正确的手机号' }]">
        </van-field>
        <br>
        <van-field
          v-model="code"
          name="code"
          center
          placeholder="请输入短信验证码"
          :rules="[{ pattern: /^\d{6}$/, message: '请填写正确的验证码' }]"
        >
          <template #button>
            <van-button size="small" @click="add">{{second===0?'发送验证码':`${second}秒后发送`}}</van-button>
          </template>
        </van-field>
        <div style="margin: 16px;">
          <van-button round block class="bgc" native-type="submit">提交</van-button>
        </div>
      </van-form>
  </div>
</template>

<script>
import { getmobile, getUser } from '@/api/user'
import { setToken } from '@/utils/storage'
export default {
  name: 'LoginPage',
  data () {
    return {
      mobile: '',
      code: '',
      second: 0,
      timer: true
    }
  },
  methods: {
    async add () {
      const res = await getmobile(this.mobile)
      console.log(this.mobile)
      console.log(res)
      // 失败
      // 成功 倒计时
      this.second = 60
      this.timer = setInterval(() => {
        this.second--
        if (this.second <= 0) clearInterval(this.timer)
      }, 1000)
    },
    // async login () {
    //   try {
    //     const res = await getUser({ mobile: this.userphone, code: this.password })
    //     console.log(res)
    //     setToken(res.data.data.token)
    //   } catch (e) {
    //     console.log(e.request.response)
    //   }
    // }
    async onSubmit (values) {
      const res = await getUser(values)
      setToken(res.data.data.token)
      this.$toast.success('登录成功！')
      this.$router.push('/')
    }
  }
}
</script>

<style lang="less" scoped>
h3 {
  font-size: 26px;
  margin-left: 20px;
}
.bgc{
  background-color: greenyellow;
}
</style>
